<template>
  <div class="shopping-cart">
    <a-list
        class="cart-list"
        :data-source="cartStore.cartItemsWithDetails"
    >
      <template #renderItem="{ item }">
        <a-list-item>
          <a-list-item-meta>
            <template #avatar>
              <img :src="item.imageUrl" :alt="item.name" style="width: 80px; height: 80px; object-fit: cover;" />
            </template>
            <template #title>
              <a href="javascript:void(0)">{{ item.name }}</a>
            </template>
            <template #description>
              <div>价格: ¥{{ item.price.toFixed(2) }}</div>
              <div>
                数量:
                <a-input-number
                    v-model:value="item.quantity"
                    :min="1"
                    :max="10"
                    @change="(value) => updateQuantity(item.productId, value)"
                />
              </div>
              <div>小计: ¥{{ (item.price * item.quantity).toFixed(2) }}</div>
            </template>
          </a-list-item-meta>
          <template #extra>
            <a-button type="link" @click="removeFromCart(item.productId)">删除</a-button>
          </template>
        </a-list-item>
      </template>
    </a-list>
    <div class="cart-summary">
      <div class="total-price">
        <span>总价: </span>
        <span class="price">¥{{ cartStore.cartTotal.toFixed(2) }}</span>
      </div>
      <a-button type="primary" size="large" @click="checkout">结算</a-button>
    </div>
  </div>
</template>

<script setup>
import { onMounted } from 'vue';
import { message } from 'ant-design-vue';
import { useProductStore,useCartStore } from '@/stores/index.js';

const cartStore = useCartStore();
const productStore = useProductStore();

const updateQuantity = async (productId, quantity) => {
  try {
    await cartStore.updateProductQuantity(productId, quantity);
    message.success('购物车已更新');
  } catch (error) {
    message.error('更新数量失败');
  }
};

const removeFromCart = async (productId) => {
  try {
    await cartStore.removeProductFromCart(productId);
    message.success('商品已从购物车中移除');
  } catch (error) {
    message.error('移除商品失败');
  }
};

const checkout = () => {
  console.log('结算，总价:', cartStore.cartTotal);
  // 实现结算逻辑
  message.success('订单已提交，即将跳转到支付页面');
};

onMounted(async () => {
  await cartStore.fetchCartItems();
  await productStore.fetchProducts();
});
</script>

<style scoped>
.cart-list {
  margin-bottom: 24px;
}

.cart-summary {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 16px;
  background-color: #f0f2f5;
  border-radius: 4px;
}

.total-price {
  font-size: 18px;
  font-weight: bold;
}

.price {
  color: #ff4d4f;
  margin-left: 8px;
}
</style>

